package org.filecollector.filecontroller.cataloguemap;

import org.filecollector.filecontroller.virtualcatalogue.VirtualCatalogue;
import org.filecollector.filecontroller.virtualcatalogue.groupname.GroupName;

import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Specific implementation of Map that contains GroupName as Key and can work with Long Keys
 */
public abstract class CatalogueMap implements Map<GroupName, VirtualCatalogue> {

    public static Optional<CatalogueMap> constructFromStream(Stream<VirtualCatalogue> catalogues) {
        var names = catalogues.map(VirtualCatalogue::getName).toList();
        for (int i = 0; i < names.size(); i++) {
            for (int j = names.size() - 1; j > i; j--) {
                if (names.get(i) == names.get(j)) {
                    continue;
                }
                if (names.get(i).isIntersected(names.get(j))) {
                    return Optional.empty();
                }
            }
        }
        return Optional.of(
                new CatalogueMapClass(
                    catalogues.collect(
                        Collectors.toConcurrentMap(
                                VirtualCatalogue::getName,
                                a -> a
                        )
                    )
                )
        );
    }
}
